﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using ServiceMonitor.Core;
using ServiceMonitor.Services;
using Sunny.UI;

namespace ServiceMonitor.Forms
{
    public partial class MainForm : Form
    {
        private readonly string _configPath;
        private readonly BindingList<MonitorConfig> _bindingConfigs = new BindingList<MonitorConfig>();
        private MonitoringService _monitorService;
        private Dictionary<string, Image> _statusImages; // 使用字典存储状态图片
        private Dictionary<MonitorConfig, TabPage> keyValuePairs = new Dictionary<MonitorConfig, TabPage>();
        public MainForm()
        {
            InitializeComponent();

            // 初始化配置路径
            _configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ServiceMonitor", "config.json");

            InitializeUI();
            InitializeMonitoring();
        }

        private void InitializeUI()
        {
            // 创建状态图标字典
            _statusImages = new Dictionary<string, Image>();
            _statusImages.Add("running", CreateColorIcon(Color.Green));
            _statusImages.Add("stopped", CreateColorIcon(Color.Red));
            _statusImages.Add("error", CreateColorIcon(Color.Orange));
            _statusImages.Add("unknown", CreateColorIcon(Color.Gray));

            dgvServices.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
            dgvServices.ColumnHeadersHeight = 35;
            dgvServices.AutoGenerateColumns = false;
            // 绑定数据
            dgvServices.DataSource = _bindingConfigs;
            dgvServices.CellFormatting += OnDgvServicesCellFormatting;

            // 启用行模板
            dgvServices.RowTemplate.Height = 30;
            dgvServices.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dgvServices.BackgroundColor = SystemColors.Window;
            dgvServices.BorderStyle = BorderStyle.Fixed3D;

            btnStartStop.Click += OnBtnStartStopClick;
            btnAdd.Click += OnBtnAddClick;
            btnEdit.Click += OnBtnEditClick;
            btnDelete.Click += OnBtnDeleteClick;
        }

        private void OnDgvServicesCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex < 0 || e.RowIndex >= _bindingConfigs.Count) return;

            var config = _bindingConfigs[e.RowIndex];

            // "状态"列 - 设置图片
            if (e.ColumnIndex == 0 && dgvServices.Columns[e.ColumnIndex].Name == "status")
            {
                string statusKey = "unknown";
                var cell = dgvServices.Rows[e.RowIndex].Cells["lastStatus"];

                if (cell != null)
                {
                    string statusText = cell.Value?.ToString() ?? "";
                    if (statusText.Contains("运行") || statusText.Contains("连接成功") || statusText.Contains("正常"))
                        statusKey = "running";
                    else if (statusText.Contains("失败"))
                        statusKey = "error";
                    else if (statusText.Contains("停止"))
                        statusKey = "stopped";
                }

                e.Value = _statusImages[statusKey];
                return;
            }

            // "类型"列
            if (e.ColumnIndex == dgvServices.Columns["type"].Index)
            {
                switch (config.Type)
                {
                    case MonitorType.Port:
                        e.Value = "端口";
                        break;
                    case MonitorType.Http:
                        e.Value = "HTTP";
                        break;
                    case MonitorType.StringBoot:
                        e.Value = "Java Jar";
                        break;
                    default:
                        e.Value = "未知";
                        break;
                }
                return;
            }

            // "详细信息"列
            if (e.ColumnIndex == dgvServices.Columns["details"].Index)
            {
                switch (config.Type)
                {
                    case MonitorType.Port:
                        e.Value = $"主机：{config.Host} 端口：{config.Port}";
                        break;
                    case MonitorType.Http:
                        e.Value = config.Url;
                        break;
                    case MonitorType.StringBoot:
                        e.Value = "路径：" + Path.GetFileName(config.JarPath);
                        break;
                    default:
                        e.Value = "N/A";
                        break;
                }
                return;
            }
        }

        private Bitmap CreateColorIcon(Color color)
        {
            var bmp = new Bitmap(16, 16);
            using (var g = Graphics.FromImage(bmp))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                g.FillEllipse(new SolidBrush(color), 0, 0, 15, 15);
                g.DrawEllipse(Pens.Black, 0, 0, 15, 15);
            }
            return bmp;
        }

        private void InitializeMonitoring()
        {
            _monitorService = new MonitoringService(LogMessage, _configPath);
            _monitorService.StatusChanged += OnServiceStatusChanged;
            LoadConfiguration();
        }

        private void LoadConfiguration()
        {
            _bindingConfigs.Clear();
            _monitorService.LoadConfigs();
            var configs = _monitorService.GetAllConfigs().ToList();
            foreach (var config in configs)
            {
                _bindingConfigs.Add(config);
            }

            // 初始化状态列
            foreach (DataGridViewRow row in dgvServices.Rows)
            {
                row.Cells["lastStatus"].Value = "未检测";
            }
        }

        private void LogMessage(string message)
        {
            if (txtLog.InvokeRequired)
            {
                txtLog.Invoke((Action)delegate { LogMessage(message); });
                return;
            }
            txtLog.AppendText($"[{DateTime.Now:HH:mm:ss}] {message}{Environment.NewLine}");
            txtLog.SelectionStart = txtLog.TextLength;
            //txtLog.ScrollToCaret();
        }

        private void OnBtnStartStopClick(object sender, EventArgs e)
        {
            if (btnStartStop.Text == "停止监控")
            {
                _monitorService.StopMonitoring();
                btnStartStop.Text = "开始监控";
            }
            else
            {
                if (_bindingConfigs.Count == 0 || _bindingConfigs.Count(c => c.IsActive) == 0)
                {
                    MessageBox.Show("没有配置活动的监控项目", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                _monitorService.StartMonitoring();
                btnStartStop.Text = "停止监控";
            }
        }

        private void OnBtnAddClick(object sender, EventArgs e)
        {
            int newId = _bindingConfigs.Count > 0
                ? _bindingConfigs.Max(c => c.Id) + 1
                : 1;

            var newConfig = new MonitorConfig
            {
                Id = newId,
                Name = $"监控项#{newId}",
                IsActive = true
            };

            using (var editor = new FrmMonitorEditor(newConfig))
            {
                if (editor.ShowDialog() == DialogResult.OK && editor.Config != null)
                {
                    _monitorService.AddConfig(editor.Config);
                    _bindingConfigs.Add(editor.Config);
                    SaveConfiguration();
                    TabPage tabPage = new TabPage($"{newConfig.Name}运行日志");
                    RichTextBox logTextBox = new RichTextBox();
                    logTextBox.Multiline = true;
                    logTextBox.Dock = DockStyle.Fill;
                    tabPage.Controls.Add(logTextBox);
                    dgvTabs.TabPages.Add(tabPage);
                    keyValuePairs.Add(newConfig, tabPage);
                }
            }
        }

        private void OnBtnEditClick(object sender, EventArgs e)
        {
            if (dgvServices.CurrentRow == null || dgvServices.CurrentRow.Index < 0)
                return;

            var config = dgvServices.CurrentRow.DataBoundItem as MonitorConfig;
            if (config == null) return;

            using (var editor = new FrmMonitorEditor(config.Clone()))
            {
                if (editor.ShowDialog() == DialogResult.OK && editor.Config != null)
                {
                    int index = dgvServices.CurrentRow.Index;
                    _monitorService.RemoveConfig(config.Id);
                    _monitorService.AddConfig(editor.Config);
                    _bindingConfigs.RemoveAt(index);
                    _bindingConfigs.Insert(index, editor.Config);
                    SaveConfiguration();
                    if (keyValuePairs.TryGetValue(config, out TabPage tabPage))
                    {
                        tabPage.Text = $"{editor.Config.Name}运行日志";
                    }
                }
            }
        }

        private void OnBtnDeleteClick(object sender, EventArgs e)
        {
            if (dgvServices.CurrentRow == null || dgvServices.CurrentRow.Index < 0)
                return;

            var config = dgvServices.CurrentRow.DataBoundItem as MonitorConfig;
            if (config == null) return;

            if (MessageBox.Show($"确定要删除 '{config.Name}' 吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                _monitorService.RemoveConfig(config.Id);
                _bindingConfigs.Remove(config);
                SaveConfiguration();
                if (keyValuePairs.TryGetValue(config, out TabPage tabPage))
                {
                    dgvTabs.TabPages.Remove(tabPage);
                    keyValuePairs.Remove(config);
                }
            }
        }

        private void SaveConfiguration()
        {
            _monitorService.SaveConfigs();
        }

        private void OnServiceStatusChanged(object sender, ServiceStatusChangedEventArgs e)
        {
            if (dgvServices.InvokeRequired)
            {
                dgvServices.Invoke((Action)delegate { OnServiceStatusChanged(sender, e); });
                return;
            }

            for (int i = 0; i < _bindingConfigs.Count; i++)
            {
                if (_bindingConfigs[i].Id != e.ConfigId) continue;

                var row = dgvServices.Rows[i];
                row.Cells["lastStatus"].Value = e.Message;

                // 强制刷新状态图像
                dgvServices.InvalidateRow(i);

                break;
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            _monitorService.StopMonitoring();
        }

        private void dgvServices_SelectionChanged(object sender, EventArgs e)
        {
            btnEdit.Enabled = dgvServices.SelectedRows.Count > 0;
            btnDelete.Enabled = dgvServices.SelectedRows.Count > 0;
        }
    }
}
